package io.vertx.guides.wiki.database

import io.vertx.core.AbstractVerticle
import io.vertx.core.AsyncResult
import io.vertx.core.Future
import io.vertx.core.Handler
import io.vertx.core.json.JsonObject
import io.vertx.core.logging.LoggerFactory
import io.vertx.ext.jdbc.JDBCClient
import java.io.FileInputStream
import java.io.InputStream
import java.util.*
import io.vertx.guides.wiki.MainVerticle
import io.vertx.serviceproxy.ProxyHelper


/**
 * Created by ashye on 2017/7/18.
 */
class WikiDatabaseVerticle : AbstractVerticle() {

    companion object {
        val CONFIG_WIKIDB_JDBC_URL = "wikidb.jdbc.url"
        val CONFIG_WIKIDB_JDBC_DRIVER_CLASS = "wikidb.jdbc.driver_class"
        val CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE = "wikidb.jdbc.max_pool_size"
        val CONFIG_WIKIDB_SQL_QUERIES_RESOURCE_FILE = "wikidb.sqlqueries.resource.file"

        val CONFIG_WIKIDB_QUEUE = "wikidb.queue"

        val LOGGER = LoggerFactory.getLogger(MainVerticle::class.java)
    }

    private fun loadSqlQueries(): MutableMap<SqlQuery, String> {
        val queriesFile: String? = config().getString(CONFIG_WIKIDB_SQL_QUERIES_RESOURCE_FILE)
        val inputStream: InputStream
        if (queriesFile != null) {
            inputStream = FileInputStream(queriesFile)
        }else {
            inputStream = javaClass.getResourceAsStream("/db-queries.properties")
        }

        val queriesProps = Properties()
        queriesProps.load(inputStream)
        inputStream.close()

        val sqlQueries = mutableMapOf<SqlQuery, String>()

        sqlQueries.put(SqlQuery.CREATE_PAGES_TABLE, queriesProps.getProperty("create-pages-table"))
        sqlQueries.put(SqlQuery.ALL_PAGES, queriesProps.getProperty("all-pages"))
        sqlQueries.put(SqlQuery.GET_PAGE, queriesProps.getProperty("get-page"))
        sqlQueries.put(SqlQuery.CREATE_PAGE, queriesProps.getProperty("create-page"))
        sqlQueries.put(SqlQuery.SAVE_PAGE, queriesProps.getProperty("save-page"))
        sqlQueries.put(SqlQuery.DELETE_PAGE, queriesProps.getProperty("delete-page"))
        return sqlQueries
    }

    override fun start(startFuture: Future<Void>) {
        val sqlQueries = loadSqlQueries()

        val dbClient = JDBCClient.createShared(vertx, JsonObject()
                .put("url", config().getString(CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:file:db/wiki"))
                .put("driver_class", config().getString(CONFIG_WIKIDB_JDBC_DRIVER_CLASS, "org.hsqldb.jdbcDriver"))
                .put("max_pool_size", config().getInteger(CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 30)));

        WikiDatabaseService.create(dbClient, sqlQueries, Handler<AsyncResult<WikiDatabaseService>> { event ->
            if (event.succeeded()) {
                ProxyHelper.registerService(WikiDatabaseService::class.java, vertx, event.result(), CONFIG_WIKIDB_QUEUE)
                startFuture.complete()
            }else {
                startFuture.fail(event.cause())
            }
        })
    }

}

